package com.xmcowell.sportpacemaster.utils.mina;

import android.util.Log;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * 客户端
 * Created by Administrator on 2017/3/14.
 */

public class MinaThread extends Thread {
    private static final String WEB_MATCH_PATH = "";
    private static final int WEB_MATCH_PORT = 3333;
    private IoSession session = null;

    @Override
    public void run() {
        Log.e("MinaThread Test","客户端连接开始。。。。。。");
        IoConnector connector = new NioSocketConnector();
        //设置连接超时时间
        connector.setConnectTimeoutMillis(30000);
        //添加过滤器
//        connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new CharsetCodecFactory()));
        connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"),
                LineDelimiter.WINDOWS.getValue(),LineDelimiter.WINDOWS.getValue())));
//        connector.setHandler(new MinaClientHandler(minaService));
        connector.setHandler(new MinaClientHandler());

        try{
            ConnectFuture future = connector.connect(new InetSocketAddress(WEB_MATCH_PATH,WEB_MATCH_PORT));
            future.awaitUninterruptibly();//等待连接创建完成
            session = future.getSession();
            session.write("start");
        }catch (Exception e){
            Log.e("MinaThread Test","客户端连接异常。。。。。"+e.toString());
        }
        session.getCloseFuture().awaitUninterruptibly();//等待连接断开
        Log.e("MinaThread Test","客户端连接断开。。。。。");
        connector.dispose();

        super.run();
    }
}
